package reflect;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * Created by 5406160@qq.com on LiBoWen 李博闻.
 *
 * @ClassName : FieldTest
 * @Author : 54061
 * @Date: 2022/2/28 17:58
 */
/*获取Class对象所对应类型中所有公共的成员变量，包括继承父类的
        * Field[] getFields();
        * 获取Class对象所对应类型中所有的成员变量，不包括继承父类的
        * Field[] getDeclaredFields();
        */
public class FieldTest {

    @Test
    public void testGetPrivateField() throws Exception {
        Class<Student> clazz = Student.class;
        //获取构造器
        Constructor<Student> constructor = clazz.getConstructor(Integer.class, String.class, Integer.class, String.class, String.class);
        Student student = constructor.newInstance(1001, "李四", 20, "男", "lisi@atguigu.com");
        System.out.println(student);
        Field ageField = clazz.getDeclaredField("age");
        //忽略该成员变量的访问权限
        ageField.setAccessible(true);
        System.out.println(ageField.get(student));
    }

    @Test
    public void testGetField() throws Exception {
        Class<Student> clazz = Student.class;
        //获取构造器
        Constructor<Student> constructor = clazz.getConstructor();
        Student student = constructor.newInstance();
        System.out.println(student);
        Field nameField = clazz.getField("name");
        //为成员变量赋值
        nameField.set(student, "张三");
        //为成员变量取值
        Object o = nameField.get(student);
        System.out.println(student);
        System.out.println(o);
    }

    @Test
    public void testGetFields(){
        Class<Student> clazz = Student.class;
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++");
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
    }

}
